package com.heima.comment.service.impl;

import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Log4j2
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    UserFeign userFeign;
    @Autowired
    GreeTextScan greeTextScan;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //检查参数
        if(dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int size=20;
        //按照文章id过滤 设置分页和排序
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(size).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentRepay> repayList = mongoTemplate.find(query, ApCommentRepay.class);
        //数据封装返回
        //用户未登录 加载数据
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.okResult(repayList);
        }
        //用户已登录 加载数据 判断当前用户点赞了那些评论
        List<String> idList = repayList.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        ArrayList<ApCommentRepayVo> resultList = new ArrayList<>();
        if(repayList!=null && apCommentRepayLikes!=null){
            repayList.stream().forEach(x->{
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(x,apCommentRepayVo);
                for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                    if(x.getId().equals(apCommentRepayLike.getCommentRepayId())){
                        apCommentRepayVo.setOperation((short) 0);
                        break;
                    }
                }
                resultList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(resultList);
        }
        return ResponseResult.okResult(repayList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //检查参数
        if(dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getContent()!=null && dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"评论字数不能超过140");
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //安全过滤
        try {
            Map map = greeTextScan.greeTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if("block".equals(suggestion)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"有违规内容");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("阿里云文本审核出现错误 {}",e.getCause());
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //保存评论
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //检查参数
        if(dto.getCommentRepayId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //点赞操作
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if(apCommentRepay!=null && dto.getOperation()==0){
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
            //保存app评论信息点赞
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);
        }else if(apCommentRepay!=null && dto.getOperation()==1){
            //取消点赞并更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes()<0 ? 0 :apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);
            //删除评论信息点赞信息
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId())
            .and("commentRepayId").is(apCommentRepay.getId())),ApCommentRepayLike.class);
        }

        //数据返回
        Map<String,Object>resultMap=new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
